// stores/auth.js
import { defineStore } from 'pinia'
import { getSsoToken, logout } from '@/api/sso'
import { getToken, getTokenExp, setToken, removeToken } from '@/utils/auth'
export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    token: getToken(),
    tokenExp: getTokenExp(),
    user: null,
  }),
  actions: {
    async login(token) {
      try {
        const response = await getSsoToken({ accessToken: token })
        // debugger;
        const { accessToken, exp } = response.data.data
        setToken(accessToken, exp)
        this.token = accessToken
        this.tokenExp = exp
        this.isLoggedIn = true
      } catch (error) {
        console.error('Login failed:', error)
        throw new Error('Login failed')
      }
    },
    async loginOut() {
      try {
        const response = await logout()
        this.isLoggedIn = false
        this.token = null
        this.user = null
        removeToken()
        return response.data.data
      } catch (error) {
        console.error('Login failed:', error)
        throw new Error('Login failed')
      }
    },
    checkAuth() {
      const token = getToken()
      if (token) {
        this.isLoggedIn = true
        this.token = token
      }
    },
  },
})
